<template>
  <a-modal
    :title="title"
    :width="700"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="取消"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="所在区域">
          <!--          labelInValue-->
          <a-select
            :options="areaIdOptions"
            @select="areaSelect"
            placeholder="请选择车位所在区域"
            v-decorator="['areaId', { rules: [{ required: true, message: '请选择区域' }] }]"
          />
        </a-form-item>
        <!--        @click.native="getAreaInfo"-->

        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="区号">
          <a-input
            placeholder="请输入区号"
            @change="systemPrompt"
            v-decorator="[
              'areaCode',
              {
                rules: [
                  { required: true, message: '请输入区号!' },
                  { max: 10, message: '车位编号最大长度为10个字符' },
                ],
              },
            ]"
          />
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="起始车位编号">

          <a-input-number
            style="width: 150px"
            :min="0"
            :max="999999"
            placeholder="请输入起始车位编号"
            v-decorator="['startNumber', { rules: [{ required: true, message: '请输入起始车位编号!' }] }]"
            @change="startNumberChange"
          />
        </a-form-item>

        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="车位数">
          <a-input-number
            style="width: 150px"
            :min="1"
            :max="999999"
            placeholder="请输入车位数"
            v-decorator="['placeNos', { rules: [{ required: true, message: '请输入车位数!' }] }]"
            @change="placeNosChange"
          />
        </a-form-item>
        <div v-if="isystemPrompt" style="margin-left: 10%; color: red">
          <span class="explain">{{ isystemPromptext }} </span>
        </div>

        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="车位类型：">
          <a-radio-group v-decorator="['spaceType', { initialValue: 1 }]">
            <a-radio style="margin-right: 10px; margin-left: 20px" :value="1"> 标准车位 </a-radio>
          </a-radio-group>
        </a-form-item>

        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="备注">
          <a-input
            placeholder=""
            v-decorator="[
              'parkSpaceRemark',
              {
                rules: [
                  { required: false, message: '' },
                  { max: 10, message: '车位编号最大长度为10个字符' },
                ],
              },
            ]"
          />
        </a-form-item>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import { getAction, httpAction } from '@api/manage'
import { getMonthlyParkInfoList } from '@api/api'

export default {
  name: 'ParkingSpaceAddModal',
  data() {
    return {
      form: this.$form.createForm(this),
      title: '',
      visible: false,
      confirmLoading: false,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      model: {},
      url: {
        add: '/parkCar/parkNumber/addNew',
        areaList: '/area/parkAreaInfo/getAreaInfos',
      },
      areaIdOptions: [],
      parkInfoList: [],
      parkCode: '',
      isystemPrompt: false,
      isystemPromptext: '提示：系统将批量创建车位号为：A001 ~ A010 ，共10个车位。',
    }
  },
  mounted() {

  },
  methods: {
    startNumberChange(value) {
      this.systemPrompt()
    },
    placeNosChange(value) {
      let startNumberValue = this.form.getFieldValue('startNumber')
      if(startNumberValue === null || startNumberValue === undefined || startNumberValue ===""){
        this.$message.error('请先输入起始车位编号!')
        return
      }
      this.systemPrompt()
    },
    // 提示：系统将批量创建车位号为，A001 ~ A010 ，共10个车位。
    systemPrompt() {
      this.$nextTick(() => {
        this.isystemPrompt = false
        if (this.isEmpty(this.form.getFieldValue('areaCode'))) {

          this.form.setFieldsValue({
            startNumber: '',
            placeNos: '',
          })

          this.$message.error('请先输入区号!')
          return
        }
        let areaCode = this.form.getFieldValue('areaCode'), // 区号
          startNumber = this.form.getFieldValue('startNumber'), // 起始车位号
          placeNos = this.form.getFieldValue('placeNos'), // 车位数
          endNumber = startNumber + placeNos - 1 // 结束车位号
        if (this.isEmpty(startNumber) || this.isEmpty(placeNos)) {
          return
        }
        if(Number(endNumber) > 999){
          this.isystemPrompt = true
          this.isystemPromptext = "当前计算的末位车位号是"+endNumber+"，创建的车位号不能大于999！"
          return
        }
        this.isystemPrompt = true
        var isystemPromptext,
          startNumberNum = String(startNumber).length,
          endNumberNum = String(endNumber).length

        isystemPromptext = `提示：系统将批量创建车位号为，${areaCode}${
          startNumberNum == 1 ? '00' : startNumberNum == 2 ? '0' : ''
        }${startNumber} ~ ${areaCode}${
          endNumberNum == 1 ? '00' : endNumberNum == 2 ? '0' : ''
        }${endNumber} ，共${placeNos}个车位`
        // }

        this.isystemPromptext = isystemPromptext
      })
    },
    /**
     * 判断变量是否为空，
     * @param  {[type]}  param 变量
     * @return {Boolean}      为空返回true，否则返回false。
     */
    isEmpty(param) {
      if (param) {
        var param_type = typeof param
        if (param_type == 'object') {
          //要判断的是【对象】或【数组】或【null】等
          if (typeof param.length == 'undefined') {
            if (JSON.stringify(param) == '{}') {
              return true //空值，空对象
            }
          } else if (param.length == 0) {
            return true //空值，空数组
          }
        } else if (param_type == 'string') {
          //如果要过滤空格等字符
          var new_param = param.trim()
          if (new_param.length == 0) {
            //空值，例如:带有空格的字符串" "。
            return true
          }
        } else if (param_type == 'boolean') {
          if (!param) {
            return true
          }
        } else if (param_type == 'number') {
          if (!param) {
            return true
          }
        }
        return false //非空值
      } else {
        if(param===0){
          //非空
          return false
        }
        return true
      }
    },
    // 查询用户车场
    initParkInfoList() {
      getMonthlyParkInfoList().then((res) => {
        const that = this
        if (res.success) {
          if (res.result) {
            that.parkInfoList = []
            res.result.forEach(parkInfo => {
              that.parkInfoList.push({
                label: parkInfo.parkName,
                value: parkInfo.parkCode,
                key: parkInfo.parkCode
              })
            })
            if (that.parkInfoList.length > 0) {
              that.form.setFieldsValue({parkCode: that.parkInfoList[0].value})
              that.form.setFieldsValue({parkName: that.parkInfoList[0].label})
              that.loadAreaList()
            }

          }
        }
      })
    },


    edit() {
      this.initParkInfoList()
      // this.areaIdOptions=[]
      this.form.resetFields()
      this.visible = true
    },
    handleOk() {
      const that = this
      // 触发表单验证
      this.form.validateFields((err, values) => {
        if (!err) {
          let formData = Object.assign(this.model, values)
          if (formData.areaId !== undefined && formData.areaId.key !== undefined) {
            formData.areaId = formData.areaId.key
          }
          if(formData.areaId===undefined || formData.areaId==='' || formData.areaId === null){
            this.$message.warning("请选择区域");
            return;
          }
          this.confirmLoading = true
          httpAction(that.url.add, formData, 'post')
            .then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.$emit('ok')
                that.close()
              } else {
                that.$message.warning(res.message)
              }
            })
            .finally(() => {
              this.confirmLoading = false
            })
        }
      })
    },
    handleCancel() {
      this.close()
    },
    close() {
      this.$emit('ok')
      this.visible = false
      this.isystemPrompt = false
    },

    areaSelect(value) {
      this.form.setFieldsValue({
        areaName: value.label
      })
    },

    loadAreaList() {
      const that = this
      if (!this.url.areaList) {
        this.$message.error('请设置this.url.areaList属性!')
        return
      }
      this.loading = true
      getAction(this.url.areaList, {}).then((res) => {
        if (res.success) {
          that.areaIdOptions = []
          res.result.forEach((area) => {
            that.areaIdOptions.push({
              value: area.id,
              label: area.areaName,
            })
          })
          if(that.areaIdOptions.length>0){
            // this.$nextTick(() => {
            that.form.setFieldsValue({areaId: that.areaIdOptions[0].value})
            that.form.setFieldsValue({ areaName: that.areaIdOptions[0].label })
            // })
          }
        } else {
          this.$message.error(res.message)
        }
        that.loading = false
      })
    },
  },
}
</script>

<style scoped>
</style>
